package com.bite.demo.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Slf4j
public class SecurityUtils {
    /**
     * 加密
     */
    public static String encrpt(String password) throws UnsupportedOperationException{
        //生成盐值
        String salt  = UUID.randomUUID().toString().replace("-", "");
        //MD5（salt+password）
        String secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        //数据库存储 盐值＋密文
        String sqlPassword = salt+secretString;
        return sqlPassword;
    }

    public static boolean verify(String password,String finalPassword) {
        if(finalPassword==null || finalPassword.length()!=64) {
            log.info("密码长度不足");
            return false;
        }
        String salt = finalPassword.substring(0,32);
        //MD5（salt+password）
        String secretString = null;
        try {
            secretString=DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        }catch (UnsupportedOperationException e) {
            log.error("getBytes 异常 e:"+e);
            throw new RuntimeException();
        }
        Boolean result =(salt+secretString).equals(finalPassword);
        return result;
    }


}
